const md = require('../../utils/md5.js');
const app = getApp();
const post = require('../../utils/post.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    model: 0,
    showtype: '众库钱包',
    pagearr: ['众库钱包', '微信', '支付宝'],
    sex: 0,
    hide: 1,
    hidecode: 1,
    payzokoo: 1,
    // code: (wx.getStorageSync('userinfo')).WalletFixQRCode
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // var code = (wx.getStorageSync('userinfo')).WalletFixQRCode;

    // if (code){
    //   this.getmq2();
    // }else{
    //   this.getmq();
    // }
    this.getmq();
    // this.tozokoo();
    // var url = "http://www.zokoo.com.cn/api/pos/voiceapi/test.php?text='众库钱包到账100000元'";
    // url = encodeURI(url);
    // this.playaudio(url);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  onUnload: function () {
    this.setData({
      hide: 0,
      hidecode: 0
    })
    wx.closeSocket();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // var code = (wx.getStorageSync('userinfo')).WalletFixQRCode;
    // console.log(code)
    // if (code) {
    //   this.tocode(1);
    // } else {
    //   this.tozokoo();
    // }
    
    this.getaccount();
    this.socket();
  },
  getaccount: function () {
    var that = this;
    var datas = {};
    datas.where = "AccID =" + wx.getStorageSync('depid');
    var datacall = function (res) {
      console.log(res);
      if (res.data.data.length > 0) {
        that.setData({
          accountinfo: res.data.data[0],
          QRCodeUrl: res.data.data[0].QRCodeUrl ? res.data.data[0].QRCodeUrl : ''
        })
        if (res.data.data[0].QRCodeUrl) {
          that.tocode(1);
          //  that.getmq2();
        } else {
          that.tozokoo();
          that.getmq();
        }
      }
    }
    var res2 = post.getdata("/BO/TR_Account/Query", datas, datacall);
  },
  socket: function () {
    var that = this;
    console.log(666)
    wx.connectSocket({
      url: 'wss://api3.zokoo.com.cn/MsgBroker/paynotice_' + wx.getStorageSync('depid') + "?id=wallet_" + wx.getStorageSync('mebid')
    })
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开！')
    })
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败，请检查！')
    })
    wx.onSocketClose(function (res) {
      console.log('WebSocket 已关闭！')
    })
    wx.onSocketMessage(function (res) {
      console.log(res)
      if (res.data) {
        var data = res.data;
        // console.log(data)
        data = JSON.parse(data); 
        data = JSON.parse(data); 
        console.log(data)
        if (data) {
          console.log(data.money)
          var url = "http://www.zokoo.com.cn/api/pos/voiceapi/test.php?text=众库到账" + data.money + "元";
          url = encodeURI(url);
          that.playaudio(url);
        }

        // wx.redirectTo({
        //   url: '/pages/success/success?name=' + res.data.data.MebName + "&photo=" + res.data.data.PhotoUrl + "&money=" + res.data.data.Money + "&paytype=收款" + "&state=" + res.data.data._BOState,
        // })
      }
      // console.log('收到服务器内容：' + res.data)
    })
  },
  chushi: function () {
    var that = this;
    var t2 = new Date();//你已知的时间
    var ts2 = t2.getTime();//转化为时间戳毫秒数
    var nts = that.data.nts;
    console.log(ts2);
    console.log(nts);
    if(nts && nts > ts2){
      return;
    }else{
      console.log(666)
    }
    that.setData({
      mebid: (wx.getStorageSync('userinfo')).MebID
    })
    var apinameIsMeb = "/Action/ZKPay/StartPayment";
    var timestamp = new Date().getTime();
    timestamp = parseInt(timestamp / 1000);
    var md5IsMeb = md.hexMD5(app.server.appid + timestamp + apinameIsMeb + app.server.appkey);
    wx.request({
      //后台接口地址
      url: app.server.url + apinameIsMeb,
      data: {
        sign: md5IsMeb,
        appid: app.server.appid,
        tmsp: timestamp,
        MebID: (wx.getStorageSync('userinfo')).MebID,
        Type: "G",
        Money: 0,
        Detail: '',
        PayPsw: '',
        AccID: wx.getStorageSync('depid')
      },
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        // this.globalData.userInfo = JSON.parse(res.data);
        console.log(res);
        that.getmq();
        var t = new Date();//你已知的时间
        var ts = t.getTime();//转化为时间戳毫秒数
        var nt = new Date();//定义一个新时间
        nt.setTime(ts + 1000 * 60 * 3);//设置新时间比旧时间多一分钟
        var nts = nt.getTime();
        if (res.data.code == 0 && res.data.data.length > 0) {
          that.setData({
            model: 0,
            payno: res.data.data,
            payimg: "https://api.zokoo.com.cn/file/qrcode/" + res.data.data,
            // detail: decribe,
            // money: money,
            nts:nts
          })
        } else {
          wx.showModal({
            title: '',
            content: res.data.msg,
          })
          return;
        }
      }
    })
  },
  setmoney: function () {
    this.setData({
      model: 1
    })
  },
  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value);
    var that = this;
    var money = parseFloat(e.detail.value.money);
    var decribe = e.detail.value.decribe;
    // return;
    if (money <= 0) {
      wx.showModal({
        title: '',
        content: '输入金额必须为正数',
      })
      return;
    }
    var apinameIsMeb = "/Action/ZKPay/StartPayment";
    var timestamp = new Date().getTime();
    timestamp = parseInt(timestamp / 1000);
    var md5IsMeb = md.hexMD5(app.server.appid + timestamp + apinameIsMeb + app.server.appkey);
    wx.request({
      //后台接口地址
      url: app.server.url + apinameIsMeb,
      data: {
        sign: md5IsMeb,
        appid: app.server.appid,
        tmsp: timestamp,
        MebID: (wx.getStorageSync('userinfo')).MebID,
        Type: "G",
        Money: money,
        Detail: '',
        PayPsw: '',
        AccID: wx.getStorageSync('depid')
      },
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        // this.globalData.userInfo = JSON.parse(res.data);
        console.log(res);
        that.getmq();
        if (res.data.code == 0 && res.data.data.length > 0) {
          that.setData({
            model: 0,
            payno: res.data.data,
            detail: decribe,
            money: money,
            payimg: "https://api.zokoo.com.cn/file/qrcode/" + res.data.data,
            payzokoo: 1,
            nts:0
          })
        } else {
          wx.showModal({
            title: '',
            content: res.data.msg,
          })
          return;
        }
      }
    })

  },
  cancer: function () {
    this.setData({
      model: 0
    })
  },
  getmq: function () {
    var that = this;
    if (that.data.hide != 1) {
      return;
    }
    var datas = {};
    datas.Key = "zkwallet/payno/" + that.data.payno;
    var datacall = function (res) {
      console.log(res);
      if (res.data.data) {
        var url = "http://www.zokoo.com.cn/api/pos/voiceapi/test.php?text=众库到账" + res.data.data.Money + "元";
        url = encodeURI(url);
        that.playaudio(url);
        wx.redirectTo({
          url: '/pages/success/success?name=' + res.data.data.MebName + "&photo=" + res.data.data.PhotoUrl + "&money=" + res.data.data.Money + "&paytype=收款" + "&state=" + res.data.data._BOState,
        })

      } else {
        that.getmq();
      }
    }
    var res2 = post.getdata("/System/GetMessages", datas, datacall);
  },
  getmq2: function () {
    var that = this;
    if (that.data.hidecode != 1) {
      return;
    }
    var depid = wx.getStorageSync('depid');
    var datas = {};
    datas.Key = "zkwallet/acc/" + depid;
    var datacall = function (res) {
      console.log(res);
      if (res.data.data) {
        var url = "http://www.zokoo.com.cn/api/pos/voiceapi/test.php?text=众库到账" + res.data.data.Money + "元";
        url = encodeURI(url);
        that.playaudio(url);
        wx.redirectTo({
          url: '/pages/success/success?name=' + res.data.data.MebName + "&photo=" + res.data.data.PhotoUrl + "&money=" + res.data.data.Money + "&paytype=收款" + "&state=" + res.data.data._BOState,
        })

      } else {
        that.getmq2();
      }
    }
    var res2 = post.getdata("/System/GetMessages", datas, datacall);
  },
  playaudio: function (url = '') {
    console.log(1);
    const innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.autoplay = true;
    innerAudioContext.src = url;
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })

  },
  tozokoo: function () {
    var that = this;
    that.chushi();
    that.setData({
      payzokoo: 1,
      payimg: "https://api.zokoo.com.cn/file/qrcode/" + that.data.payno,
      hidecode: 0,
      hide: 1,
      money: 0
    })
    // that.getmq();
  },
  tocode: function (action = 0) {
    var that = this;
    that.setData({
      payzokoo: 0,
      payimg: that.data.QRCodeUrl,
      hide: 0,
      hidecode: 1,
      code: that.data.QRCodeUrl
    })
    if (action == 1) {
      return;
    }
    // that.getmq2();
  }
})